"use client"

import PredictGraph from "@/components/echarts/prediction";
import { Button } from "@/components/ui/button";
import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, Form } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { getPremodelResult } from "@/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRequest } from "ahooks";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { number, z } from "zod";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Terminal } from "lucide-react";


interface IProps {
  name?: string
}

const formSchema = z.object({
  // username: z.string().min(2, {
  //   message: "Username must be at least 2 characters.",
  // }),
  modeltype: z.string(),
  virustype: z.string(),
  modelname: z.string(),
  predictlength: z.string(),
  // windowslength: z.string(),
  file: z.instanceof(FileList).refine((file) => file?.length == 1, 'File is required.'),

})

const PretrainingPage: React.FC<IProps> = (props) => {
  const [modelType, setModelType] = useState<string>();
  const [prediction, setPrediction] = useState<number[]>([]);
  const [real, setReal] = useState<number[]>([]);
  const [mse, setMse] = useState<number>();
  const [mae, setMae] = useState<number>();
  const [r2, setR2] = useState<number>(0);


  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      virustype: "",
    }
  });

  const fileRef = form.register("file");

  function onSubmit(values: z.infer<typeof formSchema>) {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.
    const form = new FormData();
    form.append('filename', values.file[0]);
    form.append('type', values.modeltype);
    form.append('modelname', values.modelname);
    form.append('virus', values.virustype); 
    form.append('length', values.predictlength);
    console.log('查看收到的值', form)
    runPremodelResult(form);
  }

  const { loading: isPremodelResultLoading, run: runPremodelResult } = useRequest((formdata) => {
    return getPremodelResult(formdata)
  }, {
    manual: true,
    debounceWait: 1000,
    onSuccess: (res: any) => {
      console.log('查看输出666', res);
      setReal(res.y_test);
      setPrediction(res.y_pred);
      setMae(res.mae);
      setMse(res.mse);
      setR2(res.r2)
    }
  })

  const DayLength = {
    Short: '7',
    Long: '30',
  }

  const ModelType = {
    Virus: '病毒模型',
    Stock: '金融模型',
  }

  const ModelDetail = {
    LSTM: 'lstm',
    BiLSTM: 'bilstm',
    GRU: 'gru',
    STACKModel: 'stacked',
    CNNLSTM: 'cnnlstm',
    CNN: 'cnn'
  }

  const VirusType = {
    Omicron: 'omicron',
    Delta: 'delta',
    Origin: 'origin'
  }


  return (
    <div>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
          <FormField
            control={form.control}
            name="modeltype"
            render={({ field }) => (
              <FormItem>
                <FormLabel>模型类型</FormLabel>
                <Select
                  // disabled={isLoading}
                  onValueChange={(value: string) => {
                    field.onChange(value);
                    setModelType(value);
                  }}
                // defaultValue={field.value}
                >
                  <FormControl>
                    <SelectTrigger
                      className="bg-zinc-300/50 border-0 focus:ring-0 text-black ring-offset-0 focus:ring-offset-0 capitalize outline-none"
                    >
                      <SelectValue placeholder="请选择模型类型" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {Object.values(ModelType).map((type) => (
                      <SelectItem
                        key={type}
                        value={type}
                        className="capitalize"
                      >
                        {type}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />
          {modelType === '病毒模型' ?
            <FormField
              control={form.control}
              name="virustype"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>病毒类型</FormLabel>
                  <Select
                    // disabled={isLoading}
                    onValueChange={(value: string) => {
                      field.onChange(value);
                    }}
                  // defaultValue={field.value}
                  >
                    <FormControl>
                      <SelectTrigger
                        className="bg-zinc-300/50 border-0 focus:ring-0 text-black ring-offset-0 focus:ring-offset-0 capitalize outline-none"
                      >
                        <SelectValue placeholder="请选择病毒类型" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {Object.values(VirusType).map((type) => (
                        <SelectItem
                          key={type}
                          value={type}
                          className="capitalize"
                        >
                          {type}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </FormItem>
              )}
            /> : modelType === '金融模型' ? <FormField
              control={form.control}
              name="predictlength"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>预测区间</FormLabel>
                  <Select
                    // disabled={isLoading}
                    onValueChange={(value: string) => {
                      field.onChange(value);
                    }}
                  // defaultValue={field.value}
                  >
                    <FormControl>
                      <SelectTrigger
                        className="bg-zinc-300/50 border-0 focus:ring-0 text-black ring-offset-0 focus:ring-offset-0 capitalize outline-none"
                      >
                        <SelectValue placeholder="请选择预测区间" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {Object.values(DayLength).map((type) => (
                        <SelectItem
                          key={type}
                          value={type}
                          className="capitalize"
                        >
                          {type}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </FormItem>
              )}
            /> : null}
          <FormField
            control={form.control}
            name="modelname"
            render={({ field }) => (
              <FormItem>
                <FormLabel>请选择网络类型</FormLabel>
                <Select
                  // disabled={isLoading}
                  onValueChange={field.onChange}
                // defaultValue={field.value}
                >
                  <FormControl>
                    <SelectTrigger
                      className="bg-zinc-300/50 border-0 focus:ring-0 text-black ring-offset-0 focus:ring-offset-0 capitalize outline-none"
                    >
                      <SelectValue placeholder="请选择模型" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {Object.values(ModelDetail).map((type) => (
                      <SelectItem
                        key={type}
                        value={type}
                        className="capitalize"
                      >
                        {type}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />

          {/* <FormField
            control={form.control}
            name="windowslength"
            render={({ field }) => (
              <FormItem>
                <FormLabel>时间观测窗口</FormLabel>
                <Select
                  // disabled={isLoading}
                  onValueChange={field.onChange}
                // defaultValue={field.value}
                >
                  <FormControl>
                    <SelectTrigger
                      className="bg-zinc-300/50 border-0 focus:ring-0 text-black ring-offset-0 focus:ring-offset-0 capitalize outline-none"
                    >
                      <SelectValue placeholder="请选择模型观测窗口长度" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {Object.values(DayLength).map((type) => (
                      <SelectItem
                        key={type}
                        value={type.toString()}
                        className="capitalize"
                      >
                        {type}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          /> */}

          <FormField
            control={form.control}
            name="file"
            render={({ field }) => (
              <FormItem>
                <FormLabel>
                  请上传csv文件：
                </FormLabel>
                <FormControl>
                  <Input type="file" placeholder="shadcn" {...fileRef} />
                </FormControl>
                <FormDescription>
                  请上传测试集
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button type="submit" disabled={isPremodelResultLoading} >预测</Button>
        </form>
      </Form>
      {prediction.length !== 0 && modelType == '病毒模型' ? <div>
        <PredictGraph container="predictgraph" pred={prediction} actual={real} />
        {r2 > 0.8 ? <Alert>
          <Terminal className="h-4 w-4" />
          <AlertTitle>建模完成~</AlertTitle>
          <AlertDescription>
            模型可以对当前病毒传播进行建模~
          </AlertDescription>
        </Alert> : <Alert>
          <Terminal className="h-4 w-4" />
          <AlertTitle>建模完成，效果不佳</AlertTitle>
          <AlertDescription>
            模型已无法对当前病毒传播模式进行良好地建模，需要重新训练
          </AlertDescription>
        </Alert>}



      </div> : null}
    </div>
  )
}

export default PretrainingPage;